﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;

namespace MarginTrading.Forms
{
    public partial class Transaction : Form
    {
        public Transaction()
        {
            InitializeComponent();
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {
        }

        private void CreditReceipts_Load(object sender, EventArgs e)
        {
            AcceptButton = null;
            try
            {
	            AutoCompleteStringCollection data = new AutoCompleteStringCollection();
	
	            ClientCollection clientCollection = ClientService.GetClientCollection();
	
	            for (int iI = 0; iI < clientCollection.Count; iI++)
	            {
	                data.Add(clientCollection[iI].Code);
	            }
	
	            textBoxClientCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
	            textBoxClientCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
	            textBoxClientCode.AutoCompleteCustomSource = data;
            }
            catch (System.Exception ex)
            {
            	
            }

            comboBoxTransType.SelectedIndex = 0;
        }

        private void textBoxClientCode_Leave(object sender, EventArgs e)
        {
            Client client = null;
            try
            {
                client = ClientService.GetClientByCode(textBoxClientCode.Text);
            }
            catch (System.Exception ex)
            {
                return;
            }

            if (client == null)
            {
                return;
            }
            textBoxClientName.Text = client.Surname + " " + client.Initials;
            AcceptButton = buttonOK;
        }

        private void textBoxClientCode_TextChanged(object sender, EventArgs e)
        {
            textBoxClientName.Text = "";
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private bool validateInputs()
        {
            Client client = null;
            try
            {
                client = ClientService.GetClientByCode(textBoxClientCode.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Invalid Client Code", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (client == null)
            {
                MessageBox.Show("Invalid Client Code", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            double fAmount = 0;
            if (double.TryParse(textBoxAmount.Text, out fAmount) == false)
            {
                MessageBox.Show("Invalid Amount", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            //DateTime lastUpdateTime = DateTime.MinValue;
            //try
            //{
            //    lastUpdateTime = LoanAccountServices.GetLatestUpdateTime(textBoxClientCode.Text);
            //}
            //catch (System.Exception ex)
            //{
            //    MessageBox.Show("Database read error\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

            //if (lastUpdateTime > dateTimePicker1.Value)
            //{
            //    MessageBox.Show("The Date-Time you entered is earlier than the last update time of the user data\n" + 
            //        "Enter a date which is newer than " + lastUpdateTime.ToShortDateString() + " " + lastUpdateTime.ToShortTimeString(),
            //        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}


            return true;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (validateInputs() == false)
            {
                return;
            }
            LoanAccount accountEntry = new LoanAccount();

            accountEntry.Amount = double.Parse(textBoxAmount.Text);//(double)double.Parse(textBoxAmount.Text);

            accountEntry.ClientCode = textBoxClientCode.Text;
            accountEntry.CreatedDate = dateTimePicker1.Value;
            accountEntry.Remarks = textBoxRemarks.Text;

            if (comboBoxTransType.Text == "Payment to Broker")
            {
                accountEntry.TrParticulars = "Payment on Purchases";
                accountEntry.EntryType = "PA";
                accountEntry.ReferenceNo = GetReferenceCode("PA");
                if (accountEntry.Amount < 0)
                {
                    accountEntry.Amount *= -1;
                }
            }
            else if (comboBoxTransType.Text == "Receipt from Broker")
            {
                accountEntry.TrParticulars = "Receipt on Sales";
                accountEntry.ReferenceNo = GetReferenceCode("RC");
                accountEntry.EntryType = "RC";
                if (accountEntry.Amount > 0)
                {
                    accountEntry.Amount *= -1;
                }
            }
            else if (comboBoxTransType.Text == "Payment to Client")
            {
                accountEntry.TrParticulars = "Payment to Client";
                accountEntry.ReferenceNo = GetReferenceCode("CP");  //CP: Client Payment
                accountEntry.EntryType = "CP";
                if (accountEntry.Amount < 0)
                {
                    accountEntry.Amount *= -1;
                }
            }
            else if (comboBoxTransType.Text == "Receipt from Client")
            {
                accountEntry.TrParticulars = "Receipt from Client";
                accountEntry.ReferenceNo = GetReferenceCode("CR");  //CR: Client Receipt
                accountEntry.EntryType = "CR";
                if (accountEntry.Amount > 0)
                {
                    accountEntry.Amount *= -1;
                }
            }
            else if (comboBoxTransType.Text == "Other Payment")
            {
                accountEntry.TrParticulars = textBoxRemarks.Text;
                if (accountEntry.TrParticulars == "")
                {
                    accountEntry.TrParticulars = "Not Available";
                }
                accountEntry.ReferenceNo = GetReferenceCode("OP");  //OP: Other Payment
                accountEntry.EntryType = "OP";
                if (accountEntry.Amount < 0)
                {
                    accountEntry.Amount *= -1;
                }
            }
            else if (comboBoxTransType.Text == "Other Receipt")
            {
                accountEntry.TrParticulars = textBoxRemarks.Text;
                if (accountEntry.TrParticulars == "")
                {
                    accountEntry.TrParticulars = "Not Available";
                }
                accountEntry.ReferenceNo = GetReferenceCode("OR");  //OT: Other Receipt
                accountEntry.EntryType = "OR";
                if (accountEntry.Amount > 0)
                {
                    accountEntry.Amount *= -1;
                }
            }


            //accountEntry.Balance = LoanAccountServices.GetCurrentBalance(textBoxClientCode.Text);
            //if (accountEntry.EntryType == "PA")
            //{
            //    accountEntry.Balance += accountEntry.Amount;
            //}
            //else
            //{
            //    accountEntry.Balance -= accountEntry.Amount;
            //}

            try
            {
                LoanAccountServices.Add(accountEntry);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Failed to insert the entry to database\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show("Entry added successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (checkBoxDontClose.Checked == false)
            {
                Close();
            }
            else
            {
                textBoxClientCode.Text = "";
                textBoxClientName.Text = "";
                textBoxAmount.Text = "";
                textBoxRemarks.Text = "";

                textBoxClientCode.Focus();
            }
        }

        private string GetReferenceCode(string sType)
        {
            return sType + "-" + Program.GetNextSeqNO().ToString();
        }
    }
}
